package dm.ui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.EventListenerList;

import dm.service.URLListener;
import dm.service.URLObject;
import dm.service.DownloadThread;

public class NewDowload extends JFrame implements ActionListener
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 10215L;
	
	private JFileChooser chooser = null;
	private JPanel pnCenter = null;	
	private JTextField txtAddress = null;
	private JButton cmdSelectFolder = null;
	private JButton cmdStart = null;
	private String folderPath="";
	JComboBox cboFolder = null;
	
	protected EventListenerList m_eList = new EventListenerList();
	
	GridBagLayout m_gridBagLayout = new GridBagLayout();
 	GridBagConstraints m_gridBagConstraint = new GridBagConstraints();
	
	public void addCom(Container ct, Component co, int c, int r, int nc, int nr, int ipadx, int ipady, int anchor, int fill)
 	{
 		m_gridBagConstraint.gridx = c;
 		m_gridBagConstraint.gridy = r;
 		m_gridBagConstraint.gridwidth = nc;
 		m_gridBagConstraint.gridheight = nr;
 		m_gridBagConstraint.fill = fill;
 		m_gridBagConstraint.ipadx = ipadx;
 		m_gridBagConstraint.ipady = ipady;
 		m_gridBagConstraint.anchor = anchor;
 		
 		ct.add(co, m_gridBagConstraint);
 	}
	
	public NewDowload()
	{
		super("Select folder");
		
		Container c = getContentPane();
		c.setLayout(new BorderLayout());
		initComponent(c);
	}
	
	private void initComponent(Container c )
	{
		try{
			int hor = GridBagConstraints.HORIZONTAL;
			
			pnCenter = new JPanel(m_gridBagLayout);			
			txtAddress = new JTextField(25);
			cmdStart = new JButton("Bat dau");
			cmdSelectFolder = new JButton("Chon thu muc");
			cmdStart.addActionListener(this);
			cmdSelectFolder.addActionListener(this);
			
			chooser = new JFileChooser();
			chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			
			cboFolder = new JComboBox();
			cboFolder.setEditable(true);			
			
			
			//pnSouth.add(pbar);
			
			addCom(pnCenter, new JLabel("Dia chi: "), 0, 0, 2, 1, 0, 0, GridBagConstraints.NORTH, hor);
			addCom(pnCenter, txtAddress, 3, 0, 4, 1, 0, 0, GridBagConstraints.NORTH, hor);
			
			m_gridBagConstraint.insets = new Insets(10, 0, 0, 0);
			addCom(pnCenter, new JLabel("Luu vao: "), 0, 2, 2, 1, 0, 0, GridBagConstraints.NORTH, hor);
			addCom(pnCenter, cboFolder, 3, 2, 4, 1, 0, 0, GridBagConstraints.NORTH, hor);
			
			m_gridBagConstraint.insets = new Insets(10, 10, 0, 0);
			addCom(pnCenter, cmdSelectFolder, 7, 2, 2, 1, 0, 0, GridBagConstraints.NORTH, hor);
			
			addCom(pnCenter, cmdStart, 2, 3, 2, 1, 0, 0, GridBagConstraints.NORTH, hor);
			
			c.add(pnCenter, BorderLayout.CENTER);
			
			cboFolder.addItem("D:\\temp\\hehe");
			txtAddress.setText("http://www.tuoitre.com.vn");
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	public void setFolderPath(String val)
	{
		this.folderPath = val;
	}
	
	public String getFolderPath()
	{
		File f = null;
		if(folderPath == null || folderPath.equals(""))
		{
			f = chooser.getCurrentDirectory();
			folderPath = f.getPath() +"/"+ f.getName();
		}
		
		return folderPath;
	}
	
	public void fireNewURLEvent(URLObject url, String si)
	{
		// TODO Auto-generated method stub		
		Object[] listeners = m_eList.getListenerList();
		
		// loop through each listener and pass on the event if needed
	    int numListeners = listeners.length;
	    for (int i = 0; i<numListeners; i+=2) 
	    {
	    	if (listeners[i] == URLListener.class) 
	        {
	    		// pass the event to the listeners event dispatch method
	        	((URLListener)listeners[i+1]).getNewURL(url, si);
	        }            
	     }
	}

	public void actionPerformed(ActionEvent ae)
	{
		if(ae.getSource() == cmdSelectFolder)
		{
			int iResult = -1;
			File f;
			JFrame frm = new JFrame(); 
			frm.setSize(500, 400);
			iResult = chooser.showOpenDialog(frm);
			
			if(iResult == JFileChooser.APPROVE_OPTION)
			{
				f = chooser.getSelectedFile();				
				cboFolder.setSelectedItem(f.getPath());
			}
			
		}
		
		if(ae.getSource() == cmdStart)
		{
			String url = txtAddress.getText().trim();
			String si = cboFolder.getSelectedItem().toString();
			
			if(url.equals("") || si==null || si.equals(""))
			{
				JOptionPane.showMessageDialog(this, "Chua nhap dia chi", "New download", JOptionPane.INFORMATION_MESSAGE);
				return;
			}
			
			URLObject o = getInstance(url);
			
			if(o != null)
	        {
				if(si.lastIndexOf('\\') != si.length()-1)
					si = si + "\\";
				
				fireNewURLEvent(o, si);
				this.dispose();
	        }
			
		}
	}
	
	public void addURLListener(URLListener listener)
	{
		m_eList.add(URLListener.class, listener);
	}
	
	public void removeChessItemListener(URLListener listener)
	{
		m_eList.remove(URLListener.class, listener);
	}
	
	public URLObject getInstance(String surl)
	{
		URLObject instance = isValidURL(surl);
		
		if(instance == null)
		{
			surl = "http://" + surl;
			instance = isValidURL(surl);
			
			if(instance == null)
			{
				surl = surl.replaceAll("http://", "http://www.");
				instance = isValidURL(surl);	
			}
		}		
		
		return instance;
	}
	
	private URLObject isValidURL(String surl)
	{
		URLObject instance = null;
		
		try {
	        // Create a URLConnection object for a URL
			
			System.out.println("[isValidURL] URL: " + surl);
			
	        URL url = new URL(surl);
	        URLConnection conn = url.openConnection();
	        HttpURLConnection hcon = (HttpURLConnection) conn;
	        
	        Map<String,java.util.List<String>> responseHeader = null;	        
	        String MIMEtype = null;
	        String charset = null;
	        Object content = null;
	        URL responseURL = null;
	        
	        String type = null;
	        int length;	        
	        
	        hcon.connect();
	        
	        // Get the response.
	        responseHeader    = conn.getHeaderFields();
	        responseURL       = conn.getURL( );
	        length  = conn.getContentLength( );
	        type = conn.getContentType( );
	        
	        
	        if ( type != null )
	        {
	        	instance = new URLObject();
	        	
	            String[] parts = type.split( ";" );
	            //MIMEtype = parts[0].trim( );
	            for ( int i = 1; i < parts.length && charset == null; i++ )
	            {
	                String t  = parts[i].trim( );
	                int index = t.toLowerCase( ).indexOf( "charset=" );
	                if ( index != -1 )
	                    charset = t.substring( index+8 );
	            }	            
	            
	            System.out.println("[NewDownload] " + responseURL.getFile());
	            
	            //www.tuoitre.com.vn	            
	            instance.setFileName(responseURL.getFile());
	            instance.setUrl(responseURL.getProtocol() + "://" + responseURL.getHost() + ""  + responseURL.getFile());
	            instance.setLength(length);	 	            

	            if(type.indexOf("text")>=0)
	            	instance.setContentType(DownloadThread.TEXT_FILE);
	            else
	            	instance.setContentType(DownloadThread.IMAGE_FILE);
	            
	            String filename = responseURL.getFile().trim();
	            int islash = filename.lastIndexOf('/');
	            
	            if(islash < filename.length()-1)
	            {
	            	filename = filename.substring(islash + 1, filename.length());
	            	filename.replaceAll("/", "");
	            	
	            }
	            
	            String folder = cboFolder.getSelectedItem().toString();
	            if(folder.lastIndexOf('/') != folder.length()-1)
	            	folder = folder + "\\";
	            
	            filename = folder + filename;
	            
	            if(type.indexOf("text")>=0)
	            {
	            	if(filename.trim().equals(folder))
	            		filename = filename + "index.html";
	            	
	            	instance.setFileName(filename);
	            	instance.setContentType(DownloadThread.TEXT_FILE);
	            }
	            else
	            {	            		
	            	instance.setFileName(filename);
	            	instance.setContentType(DownloadThread.IMAGE_FILE);
	            }
	        }
	        else
	        {
	        	instance = null;	        	
	        }
	        
	        hcon.disconnect();
	       
	        
	        return instance;
	    } catch (StringIndexOutOfBoundsException e)
	    {
	    	//System.out.println("[isValidURL] ERROR: " + e.toString());
	    	e.printStackTrace();
	    	return null;
	    }
	    catch(IOException ie)
	    {
	    	return null;
	    }
	    catch(NullPointerException ne)
	    {
	    	System.out.println("[isValidURL] ERROR: " + ne.toString());
	    	return null;
	    }
	}
}
